package cn.wen.yinxiu.member.server.socket.handler;

import cn.wen.yinxiu.common.toolkit.SocketChannelUtil;
import cn.wen.yinxiu.member.server.protocol.login.ReconnectRequest;
import cn.wen.yinxiu.member.service.UsersService;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @ClassName: ReconnectHandler
 * @Author: 小飞
 * @Date: 2023/5/28 14:34
 * @Description: 重连处理
 */
@Slf4j
public class ReconnectHandler extends SimpleChannelInboundHandler<ReconnectRequest> {

    private final UsersService userService;

    public ReconnectHandler(UsersService userService) {
        this.userService = userService;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ReconnectRequest msg) throws Exception {
        log.info("客户端断线重连处理。userId：{}", msg.getUserId());
        Channel channel = channelHandlerContext.channel();
        // 添加用户Channel
        SocketChannelUtil.removeUserChannelByUserId(msg.getUserId());
        SocketChannelUtil.addChannel(msg.getUserId(), channel);
        // 添加群组Channel
        List<Long> groupsIdList = userService.queryTalkBoxGroupsIdList(msg.getUserId());
        for (Long groupsId : groupsIdList) {
            SocketChannelUtil.addChannelGroup(groupsId, channel);
        }
    }
}
